/* Matthias Eckhart - ITM 12 - 22.04.2014 */

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/stat.h>
#include <sys/types.h>

#define MAX_NUM_PARAMS 3
#define BLOCKSIZE 64

void print_usage(int argc);
int checkFileDescriptors(int desc, int riptor);
void closeFileDescriptors(int s, int d);

int main(int argc, char *argv[]) {

	if (argc != MAX_NUM_PARAMS) {
		print_usage(argc);
		return EXIT_FAILURE;
	}

	char buffer[BLOCKSIZE];
	int n;
	int sourceFileDescriptor = open(argv[1], O_RDONLY);
	int destinationFileDescriptor = open(argv[2], O_WRONLY | O_CREAT | O_EXCL, 0666);

	if (checkFileDescriptors(sourceFileDescriptor, destinationFileDescriptor) == -1) return EXIT_FAILURE;

 	while((n = read(sourceFileDescriptor, buffer, BLOCKSIZE)) > 0) {
        if (write(destinationFileDescriptor, buffer, n) == -1) {
        	fprintf(stderr, "%s\n", strerror(errno));
        	closeFileDescriptors(sourceFileDescriptor, destinationFileDescriptor);
        	return EXIT_FAILURE;
        }
    }

    closeFileDescriptors(sourceFileDescriptor, destinationFileDescriptor);

	return EXIT_SUCCESS;
}

void print_usage(int argc) {
	if (argc == 1) {
		fprintf(stderr, "yacp: missing file operand\n");
	} else {
		fprintf(stderr, "yacp usage: <source> <destination>\n");
	}
}

int checkFileDescriptors(int desc, int riptor) {
	if (desc == -1 || riptor == -1) {
		fprintf(stderr, "%s\n", strerror(errno));
		closeFileDescriptors(desc, riptor);
		return -1;
	}
	return 0;
}

void closeFileDescriptors(int s, int d) {
	close(s);
	close(d);
}
